﻿/*----------------------------------------------------------------
// 公司名称：公司名称
//
// 产品名称：Gaf
//
// 创 建 人：netcasewqs
// 创建日期：2022/3/4
// 邮    箱：netcasewqs@qq.com
//
// Copyright (C) 2022 Gaf，保留所有权利。
//
//----------------------------------------------------------------*/

namespace Gaf.Impl;

internal class SharedClassLoader : ClassLoader
{
    private readonly AddinActivator _activator;
    private readonly List<Assembly> _assemblies = new();

    public SharedClassLoader(AddinActivator activator) : base(
        FileUtils.GetDllPath(activator.Addin.Location, true),
        FileUtils.GetDllPath(Path.Combine(activator.Addin.Location, Constants.UnmanagedDllPathName), false),
        AssemblyLoadContext.Default)
    {
        _activator = activator;
    }

    public override IEnumerable<Assembly> Assemblies => _assemblies;

    public override Assembly LoadAssembly(string assemblyFilePath)
    {
        var asm = _assemblyLoader.LoadFromAssemblyPath(assemblyFilePath);
        _assemblies.Add(asm);
        return asm;
    }

    protected override Assembly? OnAssemblyResolving(AssemblyLoadContext context, AssemblyName assemblyName)
    {
        if (assemblyName.Name != null)
        {
            if (_managedLibsPath.TryGetValue(assemblyName.Name, out var dllPath))
                return LoadAssembly(dllPath);
            if (_activator._framework._managedLibsPath.TryGetValue(assemblyName.Name, out dllPath))
                return LoadAssembly(dllPath);
        }

        return default;
    }

    public override void Unload()
    {
        base.Unload();
        _assemblies.Clear();
    }
}
